﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aij1.Model;
using System.Web;
using Aij1.Utils;
using DevExpress.Xpo;
using DevExpress.Data.Filtering;

namespace Aij1.BLL
{
    public class AuthData
    {
        public static S_Person GetCurrentUser(Session session)
        {
            int userId = CommOp.ToInt(HttpContext.Current.Session["UserId"]);
            if (userId > 0)
                return session.GetObjectByKey<S_Person>(userId);
            else return null;
        }

        public const string QQLoginIdName = "QQLoginId";
        public static C_Customer GetCurrentCustomer(Session session)
        {
            string qqId = WebHelper.GetCookie(QQLoginIdName);
            if (!String.IsNullOrEmpty(qqId))
            {
                return session.FindObject<C_Customer>(CriteriaOperator.Parse("QQLoginId=?", qqId));
            }
            else return null;
        }

        public static S_Person GetUserInfo(Session session, string userName)
        {
            return session.FindObject<S_Person>(CriteriaOperator.Parse("SysName=?", userName));
        }

        public static void SetCurrentUser(S_Employee employee)
        {
            HttpContext.Current.Session["UserId"] = employee.Oid;
        }

        public static void SetCurrentCustomer(C_Customer customer)
        {
            customer.LastLoginTime = DateTime.Now;
            customer.LoginTimes++;
            customer.Save();

            WebHelper.SetCookie(QQLoginIdName, customer.QQLoginId);
        }

        /// <summary>
        /// 检查用户名是否唯一
        /// </summary>
        /// <param name="person"></param>
        /// <returns></returns>
        public static bool IsUniqueName(S_Person person)
        {
            S_Person other = person.Session.FindObject<S_Person>(CriteriaOperator.Parse("SysName=?", person.SysName));
            return other == null || other == person;
        }

        /// <summary>
        /// 检查用户名唯一性并尝试生成一个唯一的名称 
        /// </summary>
        /// <param name="person"></param>
        public static void CheckAndCreateSysName(S_Person person)
        {
            int i = 1;
            while (!IsUniqueName(person))
            {
                person.SysName += i++;
            }
        }

        public static XPCollection<G_FriendLink> GetVisibleFriendLink(Session session)
        {
            return new XPCollection<G_FriendLink>(session, CriteriaOperator.Parse("Visible=1"));
        }

    }
}
